package com.ssd.controller;

import com.ssd.entity.OrderEntity;
import com.ssd.entity.OrderStatusResponse;
import com.ssd.service.OrderDetailService;
import com.ssd.service.OrderService;
import com.ssd.utils.DateUtil;
import com.ssd.view.BaseResponse;
import com.ssd.viewmodel.OrderDetailViewModel;
import com.ssd.viewmodel.OrderDetailViewVOModel;
import com.ssd.viewmodel.OrderViewModel;
import com.ssd.viewmodel.Pager;
import com.ssd.vo.CancelOrderVO;
import com.ssd.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;

/**
 * 订单控制器，负责处理与订单相关的HTTP请求
 */
@RestController
@RequestMapping("/manage/order")
@Slf4j
public class OrderController {
    @Resource
    private OrderService orderService;
    @Resource
    private OrderDetailService orderDetailService;


    /**
     * 根据订单编号查询订单状态
     *
     * @param orderNo 订单编号
     * @return 包含订单状态信息的响应
     */
    @GetMapping("/status/{orderNo}")
    public BaseResponse<OrderStatusResponse> getOrderStatus(@PathVariable String orderNo) {
        OrderStatusResponse order = orderService.getStatusByOrderNo(orderNo);
        if (order == null) {
            return new BaseResponse<>(404, "订单未找到");
        }
        return new BaseResponse<>(order);
    }

    /**
     * 前端查询用户订单
     *
     * @param pageSize 每页大小，默认为10
     * @param openId   用户标识，用于搜索特定用户的订单
     * @return 包含订单视图模型的分页器
     */
    @GetMapping("/list")
    public BaseResponse<List<OrderViewModel>> getListByOpenId(
            @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageIndex,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(value = "openId", required = false, defaultValue = "") String openId) {
        //查询订单列表
        List<OrderViewModel> orderList = orderService.getListByOpenId(pageIndex, pageSize, openId);
        //查询订单详情表
        for (OrderViewModel orderViewModel : orderList) {
            List<OrderDetailViewModel> orderDetailList = orderDetailService.getListByOrderId(orderViewModel.getId());
            orderViewModel.setOrderDetailList(orderDetailList);
        }
        return new BaseResponse<List<OrderViewModel>>(orderList);
    }

    /**
     * 后端搜索订单
     *
     * @param pageIndex
     * @param pageSize
     * @param orderNo
     * @param start
     * @param end
     * @return
     */
    @GetMapping("/search")
    public BaseResponse<Pager<OrderEntity>> search(
            @RequestParam(value = "pageIndex", required = false, defaultValue = "1") Integer pageIndex,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(value = "orderNo", required = false, defaultValue = "") String orderNo,
            @RequestParam(value = "params[beginTime]", required = false, defaultValue = "") String start,
            @RequestParam(value = "params[endTime]", required = false, defaultValue = "") String end
    ) {
        LocalDate startTime = null;
        if (!start.isEmpty()) {
            startTime = DateUtil.parseLocalDate(start, "yyyy-MM-dd");
        }
        LocalDate endTime = null;
        if (!end.isEmpty()) {
            endTime = DateUtil.parseLocalDate(end, "yyyy-MM-dd");
        }
        Pager<OrderEntity> search = orderService.search(pageIndex, pageSize, orderNo, startTime, endTime);
        return new BaseResponse<Pager<OrderEntity>>(search);
    }

    /**
     * 根据订单id查询订单
     *
     * @param orderId
     * @return
     */
    @GetMapping("/{orderId}")
    public BaseResponse<OrderViewModel> getByOrderNo(@PathVariable String orderId) {
        OrderViewModel orderViewModel = orderService.getByOrderNo(orderId);
        //查询订单详情表
        List<OrderDetailViewModel> orderDetailList = orderDetailService.getListByOrderId(orderViewModel.getId());
        orderViewModel.setOrderDetailList(orderDetailList);
        return new BaseResponse<>(orderViewModel);
    }

    @GetMapping("/getByOrderNo/{orderId}")
    public BaseResponse<OrderViewModel> getByOrderNoA(@PathVariable String orderId) {
        OrderViewModel orderViewModel = orderService.getByOrderNoA(orderId);
        //查询订单详情表
        List<OrderDetailViewVOModel> orderDetailList = orderDetailService.getListByOrderIdA(orderViewModel.getId());
        orderViewModel.setOrderDetailVOList(orderDetailList);
        return new BaseResponse<>(orderViewModel);
    }

    /**
     * 生成订单
     *
     * @param orderVO
     * @return
     */
    @PostMapping("/create")
    public BaseResponse createOrder(@RequestBody OrderVO orderVO) {
        //计算商品总金额
        Integer originalAmount = orderService.computeAmount(orderVO.getSkuInfoVOList());

        Integer finalAmount = originalAmount;

        // 如果有优惠券，则计算最终金额
        if (orderVO.getCouponType() != null) {
            switch (orderVO.getCouponType()) {
                case 1: // 满减优惠券
                    if (orderVO.getDiscountAmount() != null && finalAmount >= orderVO.getDiscountAmount() * 100) {
                        finalAmount -= orderVO.getDiscountAmount().intValue() * 100;
                    }
                    break;
                case 2: // 折扣优惠券
                    if (orderVO.getDiscountRate() != null) {
                        finalAmount = (int) Math.round(originalAmount/100 * (orderVO.getDiscountRate()*0.1));
                        finalAmount=finalAmount*100;
                    }
                    break;
                default:
                    log.warn("未知的优惠券类型");
            }
        }

        //生成订单并返回订单主键
        Long orderId = orderService.createOrder(orderVO.getOpenId(), orderVO.getInnerCode(), finalAmount ,orderVO.getProductOrderNo(),orderVO.getAddr());
        //添加订单详细商品信息
        Boolean inserted = orderDetailService.insertList(orderVO.getSkuInfoVOList(), orderId);
        return new BaseResponse(inserted);
    }

    /**
     * 取消订单
     *
     * @param cancelOrderVO
     * @return
     */
    @GetMapping("/cancel/")
    public BaseResponse cancel(CancelOrderVO cancelOrderVO) {
        return orderService.cancel(cancelOrderVO);
    }
}